//
//  CallHelpViewController.m
//  Yihubang
//
//  Created by xmy on 2016/11/24.
//  Copyright © 2016年 xmy. All rights reserved.
//

#import "CallHelpViewController.h"
#import "YiAudioRecoder.h"
#import "AlterSecurityCideViewController.h"
#import "CallHelpGuideView.h"

@interface CallHelpViewController ()<checkPasswordSuccessDelegate,CallHelpGuideViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *startRecord;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *cancelHelp;
@property (weak, nonatomic) IBOutlet UILabel *recording_label;
@property (weak, nonatomic) IBOutlet UIImageView *recordAndUpdateAnimation;
@property (strong, nonatomic) YiAudioRecoder * record;
@property (strong, nonatomic) NSNumber *littleTime ;
@property (strong, nonatomic) NSTimer * recordTimer;
@property (strong, nonatomic) NSMutableDictionary * updateDic;
@property (assign,nonatomic)  BOOL isStopTimer;
@property (strong, nonatomic) CallHelpGuideView *callHelpGuideView;

@end

@implementation CallHelpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.isStopTimer = YES;
    self.record = [[YiAudioRecoder alloc] init];
    self.littleTime = [NSNumber numberWithInt:1];
    [self.startRecord addTarget:self action:@selector(openHelp) forControlEvents:UIControlEventTouchUpInside];
    [self checkOpenHelp];
    
    // Do any additional setup after loading the view.
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [LYAuthorizedMaster audioAuthorityCheckSuccess:^(void){} fail:^(void){}];
    NSUserDefaults* userDefault = [NSUserDefaults standardUserDefaults];
    NSString* CallHelpFirst = [userDefault objectForKey:CallHelpFirstKey];
    if (CallHelpFirst == nil) {
        [self addCallHelpGuideView];
        [userDefault setBool:YES forKey:CallHelpFirstKey];
        [userDefault synchronize];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - checkOpenHelpAndSetView

-(void)checkOpenHelp{
    if(self.userClient.openTypeId){
        [self setCancelHelpButton];
        [self setCallPoliceButton];
        [self.recordAndUpdateAnimation setHidden:NO];
        [self setUpdateAnimationImgs];
        [self.delegate openHelpSuccessful:YES];
    }else{
        [self.delegate openHelpSuccessful:NO];
    }
}

//加载取消求助按钮
-(void)setCancelHelpButton{
    [UIView animateWithDuration:0.6 animations:^{
        self.cancelHelp.cornerRadius =4.f;
        [self.cancelHelp setTitle:@"取消求助" forState:UIControlStateNormal];
        [self.cancelHelp.layer setBorderWidth:1.0f];
        [self.cancelHelp.layer setBorderColor:[UIColor colorWithHex:0x29CFB2].CGColor];
    }];
    [self.cancelHelp addTarget:self action:@selector(cancelRecorder) forControlEvents:UIControlEventTouchUpInside];
}

//加载拨打110按钮
-(void)setCallPoliceButton{
    [self.view layoutIfNeeded];
    [self.callPolice mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-52);
        make.right.equalTo(self.view).with.offset(0);
        make.height.equalTo(@45);
        make.width.equalTo(@50);
    }];
    [UIView animateWithDuration:0.6 animations:^{
        [self.callPolice setImage:[UIImage imageNamed:@"callPolice-after"] forState:UIControlStateNormal];
        [self.view layoutIfNeeded];
    }];
}

//加载拨打110按钮
-(void)resetCallPoliceButton{
    [self.view layoutIfNeeded];
    [self.callPolice mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-52);
        make.height.equalTo(@54);
        make.width.equalTo(@163);
        make.centerX.equalTo(self.view);
    }];
    [UIView animateWithDuration:0.6 animations:^{
        [self.callPolice setImage:[UIImage imageNamed:@"拨打110"] forState:UIControlStateNormal];
        [self.view layoutIfNeeded];
    }];
}

//加载求助按钮
-(void)resetCancelHelpButton{
    
    [UIView animateWithDuration:0.6 animations:^{
        self.cancelHelp.layer.cornerRadius =0.f;
        [self.cancelHelp setTitle:@"求助" forState:UIControlStateNormal];
        [self.cancelHelp.layer setBorderWidth:0.f];
        [self.cancelHelp.layer setBorderColor:[UIColor clearColor].CGColor];
    }];
    [self.cancelHelp removeTarget:self action:@selector(cancelRecorder) forControlEvents:UIControlEventTouchUpInside];
}

//第一次打开app时显示帮助页面
-(void)addCallHelpGuideView{
    self.callHelpGuideView = [[UINib nibWithNibName:@"CallHelpGuideView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    self.callHelpGuideView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    self.callHelpGuideView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.callHelpGuideView];
}


#pragma mark - callHelpAndControlToRecord

-(void)prepareToRecorder{
    @weakify(self)
    [LYAuthorizedMaster locationAuthorityCheckSuccess:^(void){
        @strongify(self)
        [LYAuthorizedMaster audioAuthorityCheckSuccess:^(void){
            @strongify(self)
            [self startTimer];
            self.isStopTimer = NO;
            [self.titleLabel setHidden:NO];
            [self.record startToRecorder];
            [self.recording_label setHidden:NO];
            [self setRecordAnimationImgs];
            [self.electricWaveView addSpeedElectricWaveViewAnimation:2.f];
        } fail:^(void){
            
        }];
    } fail:^(void){
        
    }];
}

-(void)setRecordAnimationImgs{
    self.recordAndUpdateAnimation.animationImages = @[[UIImage imageNamed:@"录音3"],
                                                      [UIImage imageNamed:@"录音2"],
                                                      [UIImage imageNamed:@"录音1"]];
    self.recordAndUpdateAnimation.animationDuration = 3.0f;
    self.recordAndUpdateAnimation.animationRepeatCount =0;
    [self.recordAndUpdateAnimation startAnimating];
}
-(void)setUpdateAnimationImgs{
    self.recordAndUpdateAnimation.animationImages = @[[UIImage imageNamed:@"发送求助3"],
                                                      [UIImage imageNamed:@"发送求助2"],
                                                      [UIImage imageNamed:@"发送求助1"]];
    self.recordAndUpdateAnimation.animationDuration = 3.0f;
    self.recordAndUpdateAnimation.animationRepeatCount =0;
    [self.recordAndUpdateAnimation startAnimating];
}
-(void)recordStart{
    self.littleTime = [NSNumber numberWithInt:[self.littleTime intValue] - 1];
    self.titleLabel.text = [NSString stringWithFormat:@"%@ s",self.littleTime];
    if([self.littleTime integerValue] <= 0){
        [self stopRecordAction];
    }
}
-(void)cancelRecorder{
    UIStoryboard *MineStory = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
    AlterSecurityCideViewController * alterSecurityCideVC = [MineStory instantiateViewControllerWithIdentifier:@"AlterSecurityCideViewController"];
    alterSecurityCideVC.delegate = self;
    alterSecurityCideVC.params = @{@"isCallHelp":@"1"};
    [self pushViewController:alterSecurityCideVC];
}
-(void)checkSafePasswordSuccess{
    [self cancelRecordAction];
}

//取消求助
-(void)cancelRecordAction{
    if (!self.isStopTimer) {
        [self resetRecorderCondition];
    }
    [self.recordAndUpdateAnimation setHidden:YES];
    [self.recordAndUpdateAnimation stopAnimating];
    [self.updateDic setObject:self.userClient.openTypeId forKey:@"id"];
    [self.updateDic setObject:@"0" forKey:@"notice"];
    [self.updateDic setObject:@"1" forKey:@"is_safe"];
    [self showHUDWithString:nil];
    [self resetCancelHelpButton];
    [self resetCallPoliceButton];
    [self updateHelp];
}

//录音结束
-(void)stopRecordAction{
    [self resetRecorderCondition];
    [self.updateDic setObject:@"1" forKey:@"notice"];
    [self.updateDic setObject:@"0" forKey:@"is_safe"];
    @weakify(self)
    [self showHUDWithString:@"正在上传语音"];
    [self.recordAndUpdateAnimation stopAnimating];
    [self setUpdateAnimationImgs];
    [self.record uploadRecorderFinishedBlock:^(BaseModel * model){
        @strongify(self)
        [self.updateDic setObject:model.data[@"url"] forKey:@"voice_url"];
        [self updateHelp];
    } fail:^(BaseModel * model){
        @strongify(self)
        [self updateHelp];
    }];
}
-(void)resetRecorderCondition{
    [self.record stopToRecorder];
    [self.titleLabel setHidden:YES];
    [self.recording_label setHidden:YES];
    self.littleTime = [NSNumber numberWithInt:1];
    [self.titleLabel setText:@"1s"];
    [self.electricWaveView addSpeedElectricWaveViewAnimation:1.f];
    [self stopRecordTime];
    self.isStopTimer = YES;
}

-(void)openHelp{
    if ([self doLogin]) {
        [LYAuthorizedMaster pushNotificationAuthorityCheckSuccess:^{
            if(self.userClient.openTypeId){
                [self prepareToRecorder];
                return;
            }
            @weakify(self)
            [self getMyContract:^(void){
                @strongify(self)
                [self openHelpAfter];
            }];
        } fail:^{
            
        }];
    }
}
-(void)showAlertView{
    NSString *contactNameStr  = [NSString stringWithFormat:@"别慌! %@已经收到你的求助信息了！",self.userClient.firstContractName];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:contactNameStr delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
    [alertView show];
}
#pragma mark - AppHttpRequest

-(void)updateHelp{//更新呼救接口
    @weakify(self)
    if(![[self.updateDic  allKeys] containsObject:@"id"]){
        [self.updateDic setObject:self.userClient.openTypeId forKey:@"id"];
    }
    [[[HttpManagerCenter sharedHttpManager] updtateHelp:self.updateDic resultClass:nil] subscribeNext:^(BaseModel *model){
        @strongify(self)
        if(model.code==200){
            if([self.updateDic[@"is_safe"] isEqualToString:@"1"]){
//                [self.cancelHelp setHidden:YES];
                [self.userClient cancleHelp];
                [self.updateDic removeAllObjects];
                [self checkOpenHelp];
                [self hiddenHUDWithString:@"求助已取消" error:NO];
            }else{
                [self showAlertView];
                [self hiddenHUD];
            }
//            [self.recordAndUpdateAnimation stopAnimating];
        }else{
            [self hiddenHUDWithString:model.message error:NO];
        }
    }];
}

-(void)openHelpAfter{
    @weakify(self)
    [[[HttpManagerCenter sharedHttpManager] wantHelpWithresultClass:nil] subscribeNext:^(BaseModel *model){
        @strongify(self)
        if(model.code==200){
            [self hiddenHUDWithString:@"求助已开启" error:NO];
            [self.updateDic setObject:model.data[@"id"] forKey:@"id"];
            [self.userClient setOpenTypeStatus:@[@"2", model.data[@"id"]]];
            [self checkOpenHelp];
            [self prepareToRecorder];
            //            [self postRemoveNotification];
        }else{
            [self hiddenHUDWithString:model.message error:NO];
        }
    }];
}

-(void)getMyContract:(GetContractSuccessBlock)block{
    @weakify(self)
    if(self.userClient.firstContractName){
        block();
    }else{
        [[[HttpManagerCenter sharedHttpManager] queryContactList:nil] subscribeNext:^(BaseModel *model) {
            @strongify(self)
            NSMutableArray *array = [NSMutableArray new];
            if(model.code==200){
                array = model.data;
                if(array.count != 0){
                    NSDictionary *contactDic = array.firstObject;
                    [self.userClient changeFirstContractName:contactDic[@"name"]];
                    block();
                }else{
                    [self hiddenHUDWithString:@"请先添加紧急联系人" error:NO];
                    UIStoryboard *HelpStory = [UIStoryboard storyboardWithName:@"Mine" bundle:[NSBundle mainBundle]];
                    BaseViewController * BaseViewController = [HelpStory instantiateViewControllerWithIdentifier:@"MyContactVC"];
                    [self.navigationController pushViewController:BaseViewController animated:YES];
                }
            }else{
                [self hiddenHUDWithString:model.message error:NO];
            }
        }];
    }
}

#pragma mark - CallHelpGuideViewDelegate

-(void)jumpAction{
    [self.delegate CallHelpVCBeginGuideAction];
}

#pragma mark - lazyLoad

-(NSMutableDictionary *)updateDic{
    if(!_updateDic){
        _updateDic =[NSMutableDictionary dictionary];
    }
    return _updateDic;
}
- (NSTimer*)startTimer{
    if (!_recordTimer) {
        _recordTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                        target:self
                                                      selector:@selector(recordStart)
                                                      userInfo:nil repeats:YES];
    }
    return _recordTimer;
}

#pragma mark - dealloc

-(void)stopRecordTime{
    if([self.recordTimer isValid]){
        [self.recordTimer invalidate];
        self.recordTimer =nil;
    }
    
}
-(void)dealloc{
    if([self.recordTimer isValid]){
        [self.recordTimer invalidate];
        self.recordTimer =nil;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
